package com.levi.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.levi.enums.EnumUtil;
import com.levi.form.ShippingForm;
import com.levi.mall.mapper.ShippingMapper;
import com.levi.mall.service.ShippingService;
import com.levi.pojo.Shipping;
import com.levi.vo.ResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shentong
 * @since 2022/4/4 6:23 PM
 */
@Service
public class ShippingServiceImpl extends ServiceImpl<ShippingMapper, Shipping>
        implements ShippingService {
    @Override
    public ResponseVo<Map<String,Integer>> add(Integer uid, ShippingForm form) {
        Shipping shipping = new Shipping();
        BeanUtils.copyProperties(form,shipping);
        shipping.setUserId(uid);
        boolean result = this.save(shipping);
        if (!result){
            return ResponseVo.error(EnumUtil.ERROR);
        }
        Map<String, Integer> map = new HashMap<>();
        map.put("shippingId", shipping.getId());
        return ResponseVo.success(map);
    }

    @Override
    public ResponseVo delete(Integer uid, Integer shippingId) {
        LambdaQueryWrapper<Shipping> ew = new LambdaQueryWrapper<>();
        ew.eq(Shipping::getUserId, uid)
                .eq(Shipping::getId,shippingId);
        boolean result = this.remove(ew);
        if (!result) {
            return ResponseVo.error(EnumUtil.SHIPPING_DELETE_ERROR);
        }
        return ResponseVo.success();
    }

    @Override
    public ResponseVo update(Integer uid, Integer shippingId, ShippingForm form) {
        LambdaQueryWrapper<Shipping> ew = new LambdaQueryWrapper<>();
        ew.eq(Shipping::getUserId, uid)
                .eq(Shipping::getId, shippingId);
        Shipping shipping = this.getOne(ew);
        if (shipping == null) {
            return ResponseVo.error(EnumUtil.ERROR);
        }
        BeanUtils.copyProperties(form,shipping);
        shipping.setId(shippingId);
        shipping.setUserId(uid);
        boolean result = this.updateById(shipping);
        if (!result) {
            return ResponseVo.error(EnumUtil.ERROR);
        }
        return ResponseVo.success();
    }

    @Override
    public ResponseVo<PageInfo<Shipping>> list(Integer uid,Integer pageNum,Integer pageSize) {
        LambdaQueryWrapper<Shipping> ew = new LambdaQueryWrapper<>();
        ew.eq(Shipping::getUserId, uid)
                .orderByAsc(Shipping::getId);
        PageHelper.startPage(pageNum, pageSize);
        List<Shipping> shippingList = this.list(ew);
        PageInfo<Shipping> pageInfo = new PageInfo<>(shippingList);
        return ResponseVo.success(pageInfo);
    }
}
